package com.bobi.tfca.ui.adapter

import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.bobi.tfca.R
import com.bobi.tfca.constants.MessageStatusEnum
import com.bobi.tfca.databinding.LetterNotificationItemLayoutBinding
import com.bobi.tfca.network.client.AppCache
import com.bobi.tfca.network.response.ChatRoomResponse
import com.bobi.tfca.network.response.MessageResponse
import com.bobi.tfca.util.LogUtil
import com.bumptech.glide.Glide

class LetterAndNotificationAdapter(val fragment: Fragment, var list: ArrayList<MessageResponse>) :
    RecyclerView.Adapter<LetterAndNotificationAdapter.LetterViewHolder>() {

    private var mOnItemClickListener: OnItemClickListener? = null

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener?) {
        mOnItemClickListener = onItemClickListener
    }

    fun setItemList(letterList: ArrayList<MessageResponse>) {
        this.list = letterList
    }

    inner class LetterViewHolder(private val binding: LetterNotificationItemLayoutBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(message: MessageResponse) {
            binding.message = message
            val url = message.senderPicture
            if (url != null && url.isNotBlank() && (!"null".equals(url))) {
                Glide.with(fragment).load(url).placeholder(R.mipmap.default_avatar).into(binding.ivSenderHead)
            } else {
                Glide.with(fragment).load(R.mipmap.default_avatar).into(binding.ivSenderHead)
            }
            LogUtil.i("messagestatus:${message.messageStatus}")
            val memberId = AppCache.getMyInfo().memberId
            if (MessageStatusEnum.RECEIVED.code == message.messageStatus && memberId == message.receiverId) {
                binding.unreadMsg.visibility = View.VISIBLE
            } else {
                binding.unreadMsg.visibility = View.INVISIBLE
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LetterViewHolder {
        val itemView = LetterNotificationItemLayoutBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        val viewHolder = LetterViewHolder(itemView)
        return viewHolder
    }

    override fun getItemCount(): Int = list.size

    override fun onBindViewHolder(holder: LetterViewHolder, position: Int) {
        val message = list[position]
        with(holder) {
            bind(message)
            itemView.setOnClickListener {
                mOnItemClickListener?.onItemClick(position)
            }
        }
    }
}